const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const chalk = require('chalk');
const ora = require('ora');

class CaseWarehouseBuilder {
  constructor() {
    this.sourceDir = path.join(__dirname, '..');
    this.distDir = path.join(this.sourceDir, 'dist');
    this.demosDir = path.join(this.sourceDir, 'src', 'demos');
    this.imagesDir = path.join(this.sourceDir, 'src', 'assets', 'images');
  }

  async build() {
    const spinner = ora('开始构建项目...').start();
    
    try {
      // 1. 清理并创建dist目录
      await this.cleanDist();
      await this.createDistStructure();
      
      // 2. 复制静态资源
      await this.copyStaticAssets();
      
      // 3. 扫描并生成案例元数据
      const demos = await this.scanDemos();
      
      // 4. 生成优化的HTML文件
      await this.generateHTML(demos);
      
      // 5. 生成优化的JavaScript文件
      await this.generateJS(demos);
      
      // 6. 优化图片资源
      await this.optimizeImages();
      
      // 7. 生成图标和SEO文件
      await this.generateIconsAndSEO();
      
      spinner.succeed('项目构建完成！');
      console.log(chalk.green(`✅ 构建完成，共处理 ${demos.length} 个案例`));
      
    } catch (error) {
      spinner.fail('构建失败');
      console.error(chalk.red('构建错误:'), error.message);
      process.exit(1);
    }
  }

  async cleanDist() {
    if (fs.existsSync(this.distDir)) {
      fs.rmSync(this.distDir, { recursive: true, force: true });
    }
    fs.mkdirSync(this.distDir, { recursive: true });
  }

  async createDistStructure() {
    const dirs = ['demos', 'css', 'js', 'images', 'fonts', 'videos'];
    dirs.forEach(dir => {
      fs.mkdirSync(path.join(this.distDir, dir), { recursive: true });
    });
  }

  async scanDemos() {
    const demos = [];
    const demoFolders = fs.readdirSync(this.demosDir, { withFileTypes: true })
      .filter(dirent => dirent.isDirectory())
      .map(dirent => dirent.name)
      .sort((a, b) => {
        // 数字文件夹按数字排序，其他按字母排序
        const aNum = parseInt(a);
        const bNum = parseInt(b);
        if (!isNaN(aNum) && !isNaN(bNum)) {
          return aNum - bNum;
        }
        return a.localeCompare(b);
      });

    for (let i = 0; i < demoFolders.length; i++) {
      const folder = demoFolders[i];
      const demoPath = path.join(this.demosDir, folder);
      const demo = await this.parseDemo(folder, demoPath, i);
      if (demo) {
        demos.push(demo);
      }
    }

    return demos;
  }

  async parseDemo(folderName, demoPath, currentIndex) {
    const htmlFile = path.join(demoPath, 'index.html');
    const cssFile = path.join(demoPath, 'index.css');
    const jsFile = path.join(demoPath, 'index.js');
    
    if (!fs.existsSync(htmlFile)) {
      console.warn(chalk.yellow(`⚠️  跳过 ${folderName}: 缺少 index.html`));
      return null;
    }

    // 读取HTML内容并提取标题
    const htmlContent = fs.readFileSync(htmlFile, 'utf8');
    const titleMatch = htmlContent.match(/<title[^>]*>([^<]+)<\/title>/i);
    const title = titleMatch ? titleMatch[1].trim() : folderName;

    // 自动分类（基于文件名和内容）
    const category = this.detectCategory(folderName, htmlContent);

    // 生成预览图路径
    const previewPath = `images/previews/${folderName}.webp`;
    const srcPreviewPath = path.join(this.sourceDir, 'src', 'assets', 'images', 'previews', `${folderName}.webp`);
    const previewExists = fs.existsSync(srcPreviewPath);

    return {
      id: currentIndex + 1,
      name: title,
      category: category,
      preview: previewExists ? previewPath : 'images/previews/default.webp',
      path: `demos/${folderName}/index.html`,
      folder: folderName,
      hasCSS: fs.existsSync(cssFile),
      hasJS: fs.existsSync(jsFile),
      files: {
        html: htmlFile,
        css: fs.existsSync(cssFile) ? cssFile : null,
        js: fs.existsSync(jsFile) ? jsFile : null
      }
    };
  }

  detectCategory(folderName, htmlContent) {
    const content = (folderName + ' ' + htmlContent).toLowerCase();
    
    if (content.includes('button') || content.includes('btn')) return 'buttons';
    if (content.includes('loading') || content.includes('load')) return 'loadings';
    if (content.includes('navigation') || content.includes('nav') || content.includes('menu')) return 'navigations';
    if (content.includes('card')) return 'cards';
    if (content.includes('form') || content.includes('login') || content.includes('input')) return 'forms';
    if (content.includes('animation') || content.includes('animate')) return 'animations';
    if (content.includes('layout') || content.includes('grid')) return 'layouts';
    if (content.includes('icon')) return 'icons';
    
    return 'animations'; // 默认分类
  }

  async copyStaticAssets() {
    const assets = [
      { from: path.join(this.sourceDir, 'src', 'styles'), to: path.join(this.distDir, 'css') },
      { from: path.join(this.sourceDir, 'src', 'scripts'), to: path.join(this.distDir, 'js') },
      { from: path.join(this.sourceDir, 'src', 'assets', 'fonts'), to: path.join(this.distDir, 'fonts') },
      { from: path.join(this.sourceDir, 'src', 'assets', 'media', 'videos'), to: path.join(this.distDir, 'videos') },
      { from: path.join(this.sourceDir, 'src', 'libs'), to: path.join(this.distDir, 'libs') },
      { from: path.join(this.sourceDir, 'src', 'fonts'), to: path.join(this.distDir, 'fonts') },
      { from: path.join(this.sourceDir, 'src', 'webfonts'), to: path.join(this.distDir, 'webfonts') }
    ];
    
    for (const asset of assets) {
      if (fs.existsSync(asset.from)) {
        this.copyDir(asset.from, asset.to);
      }
    }

    // 复制demos目录并更新图标路径
    await this.copyDemosWithUpdatedPaths();
    
    // 复制images目录
    this.copyDir(this.imagesDir, path.join(this.distDir, 'images'));
  }

  copyDir(src, dest) {
    if (!fs.existsSync(dest)) {
      fs.mkdirSync(dest, { recursive: true });
    }
    
    const entries = fs.readdirSync(src, { withFileTypes: true });
    
    for (const entry of entries) {
      const srcPath = path.join(src, entry.name);
      const destPath = path.join(dest, entry.name);
      
      if (entry.isDirectory()) {
        this.copyDir(srcPath, destPath);
      } else {
        fs.copyFileSync(srcPath, destPath);
      }
    }
  }

  async copyDemosWithUpdatedPaths() {
    const demosDestDir = path.join(this.distDir, 'demos');
    
    if (!fs.existsSync(demosDestDir)) {
      fs.mkdirSync(demosDestDir, { recursive: true });
    }
    
    const demoFolders = fs.readdirSync(this.demosDir, { withFileTypes: true })
      .filter(dirent => dirent.isDirectory())
      .map(dirent => dirent.name);
    
    for (const folder of demoFolders) {
      const srcDemoPath = path.join(this.demosDir, folder);
      const destDemoPath = path.join(demosDestDir, folder);
      
      // 复制整个案例目录
      this.copyDir(srcDemoPath, destDemoPath);
      
      // 更新HTML文件中的图标路径
      const htmlPath = path.join(destDemoPath, 'index.html');
      if (fs.existsSync(htmlPath)) {
        let content = fs.readFileSync(htmlPath, 'utf8');
        
        // 将 ../../favicon.ico 替换为 ../../favicon.ico (保持不变)
        // 清理其他图标引用
        content = content.replace(/<link[^>]*(?:favicon|icon)[^>]*>/gi, '');
        content = content.replace(/\n\s*\n\s*\n/g, '\n\n');
        
        // 添加favicon.ico引用
        const faviconLink = `    <link rel="icon" type="image/x-icon" href="../../favicon.ico" />`;
        content = content.replace('</head>', `${faviconLink}\n</head>`);
        
        fs.writeFileSync(htmlPath, content);
      }
      
      // 更新CSS文件中的图片路径
      const cssPath = path.join(destDemoPath, 'index.css');
      if (fs.existsSync(cssPath)) {
        let cssContent = fs.readFileSync(cssPath, 'utf8');
        
        // 将 ../../assets/images/ 替换为 ../../images/
        cssContent = cssContent.replace(/\.\.\/\.\.\/assets\/images\//g, '../../images/');
        
        // 将 /images/ 替换为 ../../images/ (处理绝对路径)
        cssContent = cssContent.replace(/\/images\//g, '../../images/');
        
        // 修复可能出现的重复路径问题
        cssContent = cssContent.replace(/\.\.\/\.\.\/\.\.\/\.\.\/images\//g, '../../images/');
        
        // 修复错误的路径格式
        cssContent = cssContent.replace(/\.\.\/\.\.\.\.\/\.\.\/images\//g, '../../images/');
        
        fs.writeFileSync(cssPath, cssContent);
      }
    }
  }

  async generateHTML(demos) {
    const template = fs.readFileSync(path.join(this.sourceDir, 'index.html'), 'utf8');
    
    // 生成优化的HTML
    const timestamp = Date.now();
    const optimizedHTML = template
      .replace('<!-- 菜单项将通过JavaScript动态生成 -->', '')
      .replace('<!-- 展示项目将通过JavaScript动态加载 -->', '')
      .replace('<script src="js/demo.js"></script>', `<script src="js/demo.js?v=${timestamp}"></script>`)
      .replace('<script src="js/data.js"></script>', `<script src="js/data.js?v=${timestamp}"></script>`)
      .replace('<script src="js/performance.js"></script>', `<script src="js/performance.js?v=${timestamp}"></script>`)
      .replace('<script src="js/main.js"></script>', `<script src="js/main.js?v=${timestamp}"></script>`);

    fs.writeFileSync(path.join(this.distDir, 'index.html'), optimizedHTML);
  }

  async generateJS(demos) {
    // 不需要生成额外的JS文件，直接使用原有的脚本文件
    // 这里可以添加其他优化逻辑，比如压缩、合并等
    console.log(chalk.blue('📦 JavaScript文件已复制到dist目录'));
  }

  async optimizeImages() {
    // 这里可以添加图片优化逻辑
    // 例如：压缩、格式转换、生成WebP等
    console.log(chalk.blue('📸 图片优化功能待实现...'));
  }

  async generateIconsAndSEO() {
    try {
      console.log(chalk.blue('🎨 生成图标和SEO文件...'));
      
      // 复制favicon.ico到dist目录
      await this.copyFavicon();
      
      // 生成其他SEO文件
      await this.generateSEOFiles();
      
      console.log(chalk.green('✅ 图标和SEO文件生成完成'));
    } catch (error) {
      console.log(chalk.yellow('⚠️ 图标生成失败，跳过此步骤:'), error.message);
    }
  }

  async copyFavicon() {
    const faviconSrc = path.join(this.sourceDir, 'favicon.ico');
    const faviconDest = path.join(this.distDir, 'favicon.ico');
    
    if (fs.existsSync(faviconSrc)) {
      fs.copyFileSync(faviconSrc, faviconDest);
      console.log(chalk.green('✅ favicon.ico已复制到dist目录'));
    } else {
      console.log(chalk.yellow('⚠️ favicon.ico不存在'));
    }
  }

  async generateSEOFiles() {
    // 复制manifest.json
    const manifestSrc = path.join(this.sourceDir, 'public', 'manifest.json');
    const manifestDest = path.join(this.distDir, 'manifest.json');
    if (fs.existsSync(manifestSrc)) {
      fs.copyFileSync(manifestSrc, manifestDest);
    }

    // 复制robots.txt
    const robotsSrc = path.join(this.sourceDir, 'public', 'robots.txt');
    const robotsDest = path.join(this.distDir, 'robots.txt');
    if (fs.existsSync(robotsSrc)) {
      fs.copyFileSync(robotsSrc, robotsDest);
    }

    // 复制sitemap.xml
    const sitemapSrc = path.join(this.sourceDir, 'public', 'sitemap.xml');
    const sitemapDest = path.join(this.distDir, 'sitemap.xml');
    if (fs.existsSync(sitemapSrc)) {
      fs.copyFileSync(sitemapSrc, sitemapDest);
    }

    // 复制browserconfig.xml
    const browserconfigSrc = path.join(this.sourceDir, 'public', 'browserconfig.xml');
    const browserconfigDest = path.join(this.distDir, 'browserconfig.xml');
    if (fs.existsSync(browserconfigSrc)) {
      fs.copyFileSync(browserconfigSrc, browserconfigDest);
    }
  }
}

// 执行构建
if (require.main === module) {
  const builder = new CaseWarehouseBuilder();
  builder.build().catch(console.error);
}

module.exports = CaseWarehouseBuilder;
